import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/controller/browse_history_controller.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';

class BrowseHistoryPage extends StatelessWidget {
  const BrowseHistoryPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final BrowseHistoryController controller = Get.put(BrowseHistoryController());

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Get.back(),
        ),
        title: const Text(
          '浏览记录',
          style: TextStyle(color: Colors.black, fontSize: 18),
        ),
        centerTitle: true,
        actions: [
          Obx(() => controller.historyList.isNotEmpty
              ? TextButton(
                  onPressed: () => controller.clearAllHistory(),
                  child: const Text(
                    '清空',
                    style: TextStyle(color: CustomColor.primaryColor),
                  ),
                )
              : const SizedBox.shrink()),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.historyList.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.history,
                  size: 80,
                  color: Colors.grey[300],
                ),
                const SizedBox(height: 16),
                Text(
                  '暂无浏览记录',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '浏览过的故事会出现在这里',
                  style: TextStyle(
                    color: Colors.grey[400],
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          );
        }

        return ListView.builder(
          itemCount: controller.historyList.length,
          itemBuilder: (context, index) {
            final history = controller.historyList[index];
            return Dismissible(
              key: Key(history.id.toString()),
              direction: DismissDirection.endToStart,
              background: Container(
                alignment: Alignment.centerRight,
                padding: const EdgeInsets.only(right: 20),
                color: Colors.red,
                child: const Icon(
                  Icons.delete,
                  color: Colors.white,
                ),
              ),
              onDismissed: (direction) {
                controller.deleteHistory(history.id!);
              },
              child: ListTile(
                leading: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: history.coverPicture != null && history.coverPicture!.isNotEmpty
                      ? Image.network(
                          history.coverPicture!,
                          width: 56,
                          height: 56,
                          fit: BoxFit.cover,
                        )
                      : Container(
                          width: 56,
                          height: 56,
                          color: Colors.grey[200],
                          child: Icon(
                            history.type == 1 ? Icons.videocam : Icons.image,
                            color: Colors.grey[400],
                          ),
                        ),
                ),
                title: Text(
                  history.title ?? '无标题',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                subtitle: Text(
                  _formatBrowseTime(history.browseTime!),
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 12,
                  ),
                ),
                trailing: const Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: Colors.grey,
                ),
                onTap: () {
                  controller.navigateToNoteDetail(history);
                },
              ),
            );
          },
        );
      }),
    );
  }

  String _formatBrowseTime(int timestamp) {
    final now = DateTime.now();
    final browseTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    final difference = now.difference(browseTime);

    if (difference.inDays > 0) {
      if (difference.inDays == 1) {
        return '昨天';
      } else if (difference.inDays < 7) {
        return '${difference.inDays}天前';
      } else {
        return '${browseTime.year}-${browseTime.month.toString().padLeft(2, '0')}-${browseTime.day.toString().padLeft(2, '0')}';
      }
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}